import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    BopContentEditDto, BopContentInfoDto, BopContentServiceProxy, ProcessRouteServiceProxy,
    BopNodeServiceProxy, ProcessDesignDto, ProcessesEntityDto, TechniqueDto, WorkStepAndProcessDto,
    ProcessNodeDto, ProcessLineDto, MatingManagerServiceProxy
} from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { OrganizationUnitsTreeComponent } from '../shared/organization-unit-tree.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TreeNode } from 'primeng/api';
import { CreateOrEditBopTreeModalComponent } from './create-or-edit-boptree-modal.component';
import { CreateOrEditDrawModalComponent } from './create-or-edit-draw-modal.component';
import { MessageService } from '@abp/message/message.service';
import { DataExportComponent } from './data-export/data-export.component';
import { ImportBopComponent } from './import-bop/import-bop.component'
import * as moment from 'moment';
import * as go from "gojs";



@Component({
    selector: 'createOrEditBopModal',
    templateUrl: './create-or-edit-bop-modal.component.html',
    styleUrls: ['./create-or-edit-bop-modal.component.less'],

})
export class CreateOrEditBopModalComponent extends AppComponentBase {
    // gojs自带参数
    private diagram: go.Diagram = new go.Diagram();
    @ViewChild("diagramDiv")
    private diagramRef: ElementRef;
    @Input()
    get model(): go.Model {
        return this.diagram.model;
    }
    set model(val: go.Model) {
        this.diagram.model = val;
    }
    @Output()
    nodeSelected = new EventEmitter<go.Node | null>();

    @Output()
    modelChanged = new EventEmitter<go.ChangedEvent>();

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('organizationUnitTree') organizationUnitTree: OrganizationUnitsTreeComponent;
    //第一个参数是对应子组件的selector，第二个参数自定义显示到html页面，第三个参数是引入路径
    @ViewChild('createOrEditBopTreeModal') createOrEditBopTreeModal: CreateOrEditBopTreeModalComponent;
    @ViewChild('createOrEditDrawModal') createOrEditDrawModal: CreateOrEditDrawModalComponent;
    @ViewChild('dataexport') dataExport: DataExportComponent;
    @ViewChild('importBop') importBop: ImportBopComponent;
    @Input() parentInfo: any;//父级节点信息  
    active = false;
    saving = false;
    treeForm = {};
    advancedFiltersAreShown = false;
    loading: boolean;
    loadingtree: boolean;
    isReceived = true;
    isCompleted = false;
    anyncing = false;
    filterText = '';
    files2: any;//树形结构
    selectedFiles: TreeNode;
    ischeckTree: any;//当前点击节点
    bopContent: BopContentEditDto = new BopContentEditDto();
    btInfo: BopContentInfoDto = new BopContentInfoDto();//部套
    btInfoDate = undefined;// 部套新增时间
    btInfoNewDate = undefined;// 部套新增时间
    processFile: TechniqueDto = new TechniqueDto();//工艺规程
    workStepData: [];//工步动态表List
    workStepHeader: any;//工步动态表Header
    isSon: boolean = false;// 树结构儿子1
    isParent: boolean = true;// 树结构父级0
    isGrandSon: boolean = false;// 树结构孙子2
    isGrandSons: boolean = false;// 树结构孙子3
    titleName = '发次描述';
    titleLable = '发次';
    showTree = false;
    visibleSidebar = false;// 线图路弹窗
    //数据导出需要的参数
    exportData: any;
    // ischangekey:0;//右侧tab切换 0为部套 1为工艺规程
    //右侧工序信息
    processInfo: ProcessesEntityDto = new ProcessesEntityDto();
    //右侧工步信息
    workstepInfo: WorkStepAndProcessDto = new WorkStepAndProcessDto();
    //线路图固定3个参数
    mapMsg = { bopDescId: '', parentId: '', workingHourStatus: '' };
    //线路图节点信息
    nodeData: any;
    check = [];
    workStepCheck = [];
    mapForm = {
        level: undefined,
        nodeDrawingNo: undefined,
        text: '',
        workingHour: undefined,
        model: undefined,
        characteristic: undefined
    };
    canBop = false;
    saveFlag = true;
    constructor(
        injector: Injector,
        private _bopNodeServiceProxy: BopNodeServiceProxy,
        private _messageService: MessageService,
        private _bopContentServiceProxy: BopContentServiceProxy,
        private _processRouteServiceProxy: ProcessRouteServiceProxy,
        private _matingManagerServiceProxy: MatingManagerServiceProxy,
    ) {
        super(injector);

    }
    init() {

    }
    submitDetail(data) {
        let reg = /^((\d{1,2}(\.\d{1,2})?))$/;
        console.log(data.workingHours);
        
        console.log(reg.test(data.workingHours));
        if (reg.test(data.workingHours)) {
            this._bopNodeServiceProxy
                .updateWorkingHours(data.id, data.workingHours)
                .subscribe(() => { });
        }else{
            this._messageService.error('小数点后最多输入两位小数');
            return;
        }

    }

    bopImport() {
        // bop引入
        this.importBop.show();
    }
    onHide(event) {
        //关闭线路图弹窗
        this.mapForm.nodeDrawingNo = undefined;
        this.mapForm.model = undefined;
        this.mapForm.text = '';
        this.mapForm.characteristic = undefined;
        this.mapForm.workingHour = undefined;
    }
    saveLineNode(row) {
        if (row.key != undefined) {
            this._matingManagerServiceProxy
                .getRouteType(row.key)
                .subscribe((rs) => {
                    this.nodeData = row;
                    // 节点
                    this.visibleSidebar = true;
                    this.mapForm.level = rs;
                    this.mapForm.text = row.text;
                    this.mapForm.characteristic = row.characteristic;
                    this.mapForm.nodeDrawingNo = row.nodeDrawingNo;
                    this.mapForm.workingHour = row.workingHour;
                });
        } else {
            // 线
            this.visibleSidebar = false;
        }
    }
    // 保存线路图
    saveMap() {
        let parm = new ProcessDesignDto();
        parm.bopDescId = this.mapMsg.bopDescId;
        parm.parentId = this.mapMsg.parentId;
        parm.workingHourStatus = this.mapMsg.workingHourStatus;
        parm.processLineList = [];
        parm.processNodeList = [];
        for (const item of this.diagram.model.nodeDataArray) {
            let processNodeList = new ProcessNodeDto();
            processNodeList.color = item.color;
            processNodeList.details = item.details;
            processNodeList.figure = item.figure;
            processNodeList.fill = item.fill;
            processNodeList.key = item.key;
            processNodeList.loc = item.loc;
            processNodeList.nodeDrawingNo = item.nodeDrawingNo;
            processNodeList.parentId = item.parentId;
            processNodeList.size = item.size;
            processNodeList.sort = item.sort;
            processNodeList.text = item.text;
            processNodeList.workingHour = item.workingHour;
            parm.processNodeList.push(processNodeList);
        }
        for (const item of this.diagram.model.linkDataArray) {
            let processLineDto = new ProcessLineDto();
            if (item.color) {
                processLineDto.color = item.color;
            }
            processLineDto.from = item.from;
            processLineDto.to = item.to;
            processLineDto.points = JSON.stringify(item.points);
            parm.processLineList.push(processLineDto);
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._processRouteServiceProxy.saveProcess(
                parm
            )
                .pipe(finalize(() => { this.loading = false; }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        if (result.flag) {
                            this.message.confirm(
                                '已成功保存工艺路线信息，是否继续维护工时？',
                                (isConfirmed) => {
                                    if (isConfirmed) {
                                        this._processRouteServiceProxy
                                            .censusWorkTime(this.mapMsg.workingHourStatus, this.ischeckTree.id)
                                            .subscribe(() => {
                                                this._messageService.success('维护工时成功');
                                                this.nodeData = undefined;
                                                this.mapForm.level = undefined;
                                                this.mapForm.nodeDrawingNo = undefined;
                                                this.mapForm.text = '';
                                                this.mapForm.characteristic = undefined;
                                                this.mapForm.workingHour = undefined;
                                                this.mapForm.model = undefined;
                                                this.mapMsg.parentId = undefined;
                                            });
                                    } else {
                                        this.nodeData = undefined;
                                        this.mapForm.level = undefined;
                                        this.mapForm.nodeDrawingNo = undefined;
                                        this.mapForm.text = '';
                                        this.mapForm.workingHour = undefined;
                                        this.mapForm.model = undefined;
                                        this.mapMsg.parentId = undefined;
                                        this.mapForm.characteristic = undefined;
                                    }
                                }
                            );
                        } else {
                            this._messageService.success('工艺路线保存成功！');
                            this.nodeData = undefined;
                            this.mapForm.level = undefined;
                            this.mapForm.nodeDrawingNo = undefined;
                            this.mapForm.text = '';
                            this.mapForm.characteristic = undefined;
                            this.mapForm.workingHour = undefined;
                            this.mapForm.model = undefined;
                            this.mapMsg.parentId = undefined;
                        }
                    } else {
                        this._messageService.error(result.message);
                    }

                });
        }
    }
    saveMapItem() {
        //暂时保存节点信息
        this.diagram.model.nodeDataArray.forEach(i => {
            if (i.key == this.nodeData.key) {
                i.nodeDrawingNo = this.mapForm.nodeDrawingNo;
                i.text = this.mapForm.text;
                i.workingHour = this.mapForm.workingHour;
                // i.model = this.mapForm.model;
            }
        });
        this.nodeData = undefined;
        this.mapForm.nodeDrawingNo = undefined;
        this.mapForm.text = '';
        this.mapForm.characteristic = undefined;
        this.mapForm.workingHour = undefined;
        this.mapForm.model = undefined;
        let model = this.diagram.model.toJson();
        this.diagram.model = go.Model.fromJson(model);
        this.visibleSidebar = false;
    }
    //打开弹窗
    onShown(): void {
        this.mapMsg.workingHourStatus = this.parentInfo.workingHourStatus;
        this.mapMsg.bopDescId = this.parentInfo.id;
        let that = this;
        const $ = go.GraphObject.make;
        this.diagram = new go.Diagram();
        this.diagram.initialContentAlignment = go.Spot.Center;
        this.diagram.allowDrop = true; // necessary for dragging from Palette
        //  this.diagram.undoManager.isEnabled = true;
        this.diagram.grid.visible = true; //画布上面是否出现网格
        this.diagram.commandHandler.copiesTree = true; //允许使用ctrl+c、ctrl+v复制粘贴
        this.diagram.toolManager.clickCreatingTool.archetypeNodeData = {
            text: "Node",
            color: "black",
            fill: "white",
        };
        this.diagram.addModelChangedListener(function (evt) {
            if (evt.isTransactionFinished) {
                if (evt.oldValue == "ClickCreating") {
                    let guid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                    let guidCode = guid + guid + "-" + guid + "-" + guid + "-" + guid + "-" + guid + guid + guid;
                    evt.model.setKeyForNodeData(evt.model.nodeDataArray[evt.model.nodeDataArray.length - 1], guidCode);
                }
            }
        });
        var myContextMenu = $(
            "ContextMenu",
            $(
                "ContextMenuButton",
                $(
                    go.Panel,
                    "Horizontal",
                    FigureButton("Rectangle", null), FigureButton("RoundedRectangle", null), FigureButton("Ellipse", null), FigureButton("Diamond", null)
                ),
            ),
            LightFillButtons(),
            DarkColorButtons()
        );

        this.diagram.nodeTemplate = $(
            go.Node,
            "Auto",
            {
                contextMenu: myContextMenu,
                resizable: true
            },
            new go.Binding("location", "loc", go.Point.parse).makeTwoWay(
                go.Point.stringify
            ),
            $(
                go.Shape,
                "RoundedRectangle",
                {
                    fill: "white",
                    strokeWidth: 1,
                    portId: "",
                    cursor: "pointer",
                    // allow many kinds of links
                    fromLinkable: true,
                    toLinkable: true,
                    fromLinkableSelfNode: true,
                    toLinkableSelfNode: true,
                    fromLinkableDuplicates: true,
                    toLinkableDuplicates: true,
                },
                new go.Binding("fill"),
                new go.Binding("figure"),
                new go.Binding("stroke", "color"),
                new go.Binding("strokeWidth", "thickness"),
                new go.Binding("strokeDashArray", "dash"),
            ),
            {
                click: function (e, obj) {
                    e.handled = true; // don't let the click bubble up
                    e.diagram.commit(function (m) {
                        // m.model.set(obj.part.data, "color", "green");
                    });
                },
            },
            $(
                go.TextBlock,
                { margin: 8, editable: true },
                new go.Binding("text").makeTwoWay()
            )
        );

        this.diagram.linkTemplate = $(
            go.Link,
            {
                routing: go.Link.AvoidsNodes, corner: 1,
                toShortLength: 4,  // assume arrowhead at "to" end, need to avoid bad appearance when path is thick
                relinkableFrom: true, relinkableTo: true,
                reshapable: true, resegmentable: true
                // layerName: "Foreground",
                // routing: go.Link.AvoidsNodes, corner: 10,
                // toShortLength: 4,  // assume arrowhead at "to" end, need to avoid bad appearance when path is thick
                // relinkableFrom: true, relinkableTo: true,
                // reshapable: true, resegmentable: true
            },
            new go.Binding("fromSpot", "fromSpot", go.Spot.parse),
            new go.Binding("toSpot", "toSpot", go.Spot.parse),
            new go.Binding("fromShortLength", "dir", function (dir) { return dir === 2 ? 4 : 0; }),
            new go.Binding("toShortLength", "dir", function (dir) { return dir >= 1 ? 4 : 0; }),
            new go.Binding("points").makeTwoWay(),  // TwoWay due to user reshaping with LinkReshapingTool
            $(go.Shape, { strokeWidth: 1 },
                new go.Binding("stroke", "color"),
                new go.Binding("strokeWidth", "thickness"),
                new go.Binding("strokeDashArray", "dash")
            ),
            $(go.Shape, { fromArrow: "Backward", strokeWidth: 0, scale: 4 / 3, visible: false },
                new go.Binding("visible", "dir", function (dir) { return dir === 2; }),
                new go.Binding("fill", "color"),
                new go.Binding("scale", "thickness", function (t) { return (2 + t) / 3; })),
            $(go.Shape, { toArrow: "Standard", strokeWidth: 0, scale: 4 / 3 },
                new go.Binding("visible", "dir", function (dir) { return dir >= 1; }),
                new go.Binding("fill", "color"),
                new go.Binding("scale", "thickness", function (t) { return (2 + t) / 3; })),
            $(go.TextBlock,
                { alignmentFocus: new go.Spot(0, 1, -4, 0), editable: true },
                new go.Binding("text").makeTwoWay(),  // TwoWay due to user editing with TextEditingTool
                new go.Binding("stroke", "color"))
        );
        this.diagram.linkTemplate.contextMenu =
            $("ContextMenu",
                DarkColorButtons(),
                //   $("ContextMenuButton",
                //     $(go.Panel, "Horizontal",
                //       ArrowButton(0), ArrowButton(1), ArrowButton(2)
                //     )
                //   )
                //   $("ContextMenuButton",
                //     $(go.Panel, "Horizontal",
                //       $(go.Panel, "Spot",
                //         AllSidesButton(false),
                //         SpotButton(go.Spot.Top, false), SpotButton(go.Spot.Left, false), SpotButton(go.Spot.Right, false), SpotButton(go.Spot.Bottom, false)
                //       ),
                //       $(go.Panel, "Spot",
                //         { margin: new go.Margin(0, 0, 0, 2) },
                //         AllSidesButton(true),
                //         SpotButton(go.Spot.Top, true), SpotButton(go.Spot.Left, true), SpotButton(go.Spot.Right, true), SpotButton(go.Spot.Bottom, true)
                //       )
                //     )
                //   )
            );
        var nodeDataArray = [
            //{ key: 'f884f884-f884-f884-f884-f884f884f884', text: "Alpha", color: "lightblue" },
            //{ key: 'f884f885-f885-f885-f885-f885f885f885', text: "Beta", color: "orange" },
            // { key: 'f886f886-f886-f886-f886-f886f886f886', text: "Gamma", color: "lightgreen", group: 5 },
            // { key: 'f887f887-f887-f887-f887-f887f887f887', text: "Delta", color: "pink", group: 5 },
            // { key: 'f888f888-f888-f888-f888-f888f888f888', text: "Epsilon", color: "green", isGroup: true },
        ];
        var linkDataArray = [
            ///{ from: 'f884f884-f884-f884-f884-f884f884f884', to: 'f884f885-f885-f885-f885-f885f885f885' },
            // { from: 2, to: 2 },
            // { from: 3, to: 4, color: "green" },
            // { from: 3, to: 1, color: "purple" },
        ];
        this.diagram.model = new go.GraphLinksModel(
            nodeDataArray,
            linkDataArray
        );
        function ClickFunction(propname, value) {
            return function (e, obj) {
                e.handled = true;  // don't let the click bubble up
                e.diagram.model.commit(function (m) {
                    m.set(obj.part.adornedPart.data, propname, value);
                });
            };
        }
        //背景色
        function LightFillButtons() {  // used by multiple context menus
            return [
                $("ContextMenuButton",
                    $(go.Panel, "Horizontal",
                        ColorButton("white", "fill"), ColorButton("beige", "fill"), ColorButton("aliceblue", "fill"), ColorButton("lightyellow", "fill")
                    )
                ),
                $("ContextMenuButton",
                    $(go.Panel, "Horizontal",
                        ColorButton("lightgray", "fill"), ColorButton("lightgreen", "fill"), ColorButton("lightblue", "fill"), ColorButton("pink", "fill")
                    )
                )
            ];
        }
        //字体颜色和线条颜色
        function DarkColorButtons() {  // used by multiple context menus
            return [
                $("ContextMenuButton",
                    $(go.Panel, "Horizontal",
                        ColorButton("black", "color"), ColorButton("green", "color"), ColorButton("blue", "color"), ColorButton("red", "color")
                    )
                ),
                $("ContextMenuButton",
                    $(go.Panel, "Horizontal",
                        ColorButton("brown", "color"), ColorButton("magenta", "color"), ColorButton("purple", "color"), ColorButton("orange", "color")
                    )
                )
            ];
        }
        //改变颜色
        function ColorButton(color, propname) {
            if (!propname) propname = "color";
            return $(go.Shape,
                {
                    width: 16, height: 16, stroke: "lightgray", fill: color,
                    margin: 1, background: "transparent",
                    mouseEnter: function (e, shape) { shape.stroke = "dodgerblue"; },
                    mouseLeave: function (e, shape) { shape.stroke = "lightgray"; },
                    click: ClickFunction(propname, color), contextClick: ClickFunction(propname, color)
                });
        }
        //改变形状
        function FigureButton(fig, propname) {
            if (!propname) propname = "figure";
            return $(go.Shape,
                {
                    width: 32, height: 32, scale: 0.5, fill: "lightgray", figure: fig,
                    margin: 1, background: "transparent",
                    mouseEnter: function (e, shape) { shape.fill = "dodgerblue"; },
                    mouseLeave: function (e, shape) { shape.fill = "lightgray"; },
                    click: ClickFunction(propname, fig), contextClick: ClickFunction(propname, fig)
                });
        }
        function ArrowButton(num) {
            var geo = "M0 0 M16 16 M0 8 L16 8  M12 11 L16 8 L12 5";
            if (num === 0) {
                geo = "M0 0 M16 16 M0 8 L16 8";
            } else if (num === 2) {
                geo = "M0 0 M16 16 M0 8 L16 8  M12 11 L16 8 L12 5  M4 11 L0 8 L4 5";
            }
            return $(go.Shape,
                {
                    geometryString: geo,
                    margin: 2, background: "transparent",
                    mouseEnter: function (e, shape) { shape.background = "dodgerblue"; },
                    mouseLeave: function (e, shape) { shape.background = "transparent"; },
                    click: ClickFunction("dir", num), contextClick: ClickFunction("dir", num)
                });
        }
        function AllSidesButton(to) {
            var setter = function (e, shape) {
                e.handled = true;
                e.diagram.model.commit(function (m) {
                    var link = shape.part.adornedPart;
                    m.set(link.data, (to ? "toSpot" : "fromSpot"), go.Spot.stringify(go.Spot.AllSides));
                    // re-spread the connections of other links connected with the node
                    (to ? link.toNode : link.fromNode).invalidateConnectedLinks();
                });
            };
            return $(go.Shape,
                {
                    width: 12, height: 12, fill: "transparent",
                    mouseEnter: function (e, shape) { shape.background = "dodgerblue"; },
                    mouseLeave: function (e, shape) { shape.background = "transparent"; },
                    click: setter, contextClick: setter
                });
        }
        function SpotButton(spot, to) {

            var ang = 0;
            var side = go.Spot.RightSide;
            if (spot.equals(go.Spot.Top)) { ang = 270; side = go.Spot.TopSide; }
            else if (spot.equals(go.Spot.Left)) { ang = 180; side = go.Spot.LeftSide; }
            else if (spot.equals(go.Spot.Bottom)) { ang = 90; side = go.Spot.BottomSide; }
            if (!to) ang -= 180;
            var setter = function (e, shape) {
                e.handled = true;
                e.diagram.model.commit(function (m) {
                    var link = shape.part.adornedPart;
                    m.set(link.data, (to ? "toSpot" : "fromSpot"), go.Spot.stringify(side));
                    // re-spread the connections of other links connected with the node
                    (to ? link.toNode : link.fromNode).invalidateConnectedLinks();
                });
            };
            return $(go.Shape,
                {
                    alignment: spot, alignmentFocus: spot.opposite(),
                    geometryString: "M0 0 M12 12 M12 6 L1 6 L4 4 M1 6 L4 8",
                    angle: ang,
                    background: "transparent",
                    mouseEnter: function (e, shape) { shape.background = "dodgerblue"; },
                    mouseLeave: function (e, shape) { shape.background = "transparent"; },
                    click: setter, contextClick: setter
                });
        }
        this.diagram.commandHandler.doKeyDown = function () {
            var e = this.diagram.lastInput;
            // Meta（Command）键代替Mac命令的“控制”
            var key = e.key;
            //退出任何撤销/重做组合键，具体键值根据需求而定
            if (key === 'Del') {
                if (!that.visibleSidebar) {
                    go.CommandHandler.prototype.doKeyDown.call(this);
                } else {
                    that._processRouteServiceProxy.deleteChechkNode(
                        that.nodeData.key
                    )
                        .pipe(finalize(() => { }))
                        .subscribe(result => {
                            if (result) {
                                //调用没有参数的基础方法（默认功能）
                                go.CommandHandler.prototype.doKeyDown.call(this);
                            } else {
                                that._messageService.error("该节点下含有子节点不可删除！");
                                return;
                            }
                        });
                }


            }

        };
        this.diagram.addDiagramListener('ObjectSingleClicked', function (e) {
            var lineNode = e.subject.part.data;
            // 当前点击的节点信息
            that.saveLineNode(lineNode);
        });
    }
    //导入工艺规程
    toExcelDraw(): void {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        this.createOrEditDrawModal.show();
    }
    //获取树结构
    getTreeInfo(content): void {
        this.loadingtree = true;
        this._bopNodeServiceProxy.getTreeGrid(this.parentInfo.id)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                if (result.length == 0 || Object.keys(result).length == 0) {
                    this.canBop = true;
                } else {
                    this.canBop = false;
                }
                let oldNode = this.files2;
                //建立父级节点
                this.files2 = [{ id: this.parentInfo.id, key: -1, nodeDrawingNo: this.parentInfo.drawingNo, nodeName: this.parentInfo.modelName, model: this.parentInfo.model, lotNo: this.parentInfo.lotNo, stageSign: this.parentInfo.stageSign, children: result ? result : [] }];
                if (!content) {
                    this.expandAll();
                }
                if (content) {
                    this.exdents(oldNode);
                }
                this.ischeckTree = {};
                this.loadingtree = false;
            });
    }
    //点击树节点
    nodeSelect(event): void {
        this.ischeckTree = event.node;
        //如果未关联 则差右侧
        if (this.ischeckTree.nodeLevel == undefined) {
            this.titleLable = '发次描述';
            this.titleName = '发次';
            this.isSon = false;
            this.isGrandSon = false;
            this.isParent = true;
            this.isGrandSons = false;
        }
        if (this.ischeckTree.nodeLevel == 1) {
            this.titleLable = '芯级描述';
            this.titleName = '芯级';
            this.isSon = true;
            this.isGrandSon = false;
            this.isParent = false;
            this.isGrandSons = false;
        }
        if (this.ischeckTree.nodeLevel == 2) {
            this.titleLable = '部套描述';
            this.titleName = '部套';
            this.isSon = false;
            this.isGrandSon = true;
            this.isParent = false;
            this.isGrandSons = false;
        }
        if (this.ischeckTree.nodeLevel == 3) {
            this.titleLable = '工作项目描述';
            this.titleName = '工作项目';
            this.isSon = false;
            this.isGrandSon = false;
            this.isParent = false;
            this.isGrandSons = true;
        }
        if (parseInt(this.ischeckTree.nodeLevel) != 8 && parseInt(this.ischeckTree.nodeLevel) != 9) {
            this._bopContentServiceProxy.getBopContentInfoList(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.btInfo = result;
                    this.btInfoDate = undefined;
                    this.btInfoNewDate = undefined;
                    if (result.relationDate != undefined) {
                        this.btInfoDate = moment(result.relationDate).format('YYYY-MM-DD HH:mm:ss');
                    }
                    if (result.exportDate != undefined) {
                        this.btInfoNewDate = moment(result.exportDate).format('YYYY-MM-DD HH:mm:ss');
                    }
                    var tarDiv = document.getElementById("pane1");

                    if (tarDiv != null) {
                        while (tarDiv.hasChildNodes()) {
                            tarDiv.removeChild(tarDiv.firstChild);
                        }
                        var newDiv = document.createElement("div");
                        newDiv.innerHTML = this.btInfo.techniqueExplain;
                        tarDiv.appendChild(newDiv);
                    }

                });
            this._bopNodeServiceProxy.getTechniqueEntity(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.processFile = result;

                });
        }
        //已关联查出下面工序和工步
        if (this.ischeckTree.isRelation == 1) {
            this.loadingtree = true;
            this._bopNodeServiceProxy.getWorkStep(event.node.id)
                .pipe(finalize(() => { this.loadingtree = false; }))
                .subscribe(result => {
                    let rowInfo = this.getTreeRecursion(this.files2, this.ischeckTree.id);
                    rowInfo.children = result;
                });
        }
        //工序查看右侧
        if (parseInt(this.ischeckTree.nodeLevel) == 8) {
            this.check = [];
            // abp.ui.setBusy(undefined, '', 1);
            this._bopNodeServiceProxy.getProcessesById(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.processInfo = result;
                    let item = [];
                    if (this.processInfo.processesCharacteristic != null) {
                        item = this.processInfo.processesCharacteristic.split('|');
                    }
                    this.check = item;
                    this.check.splice(this.check.length - 1, 1);
                    // abp.ui.clearBusy();
                });
        }
        //工步查看右侧
        if (parseInt(this.ischeckTree.nodeLevel) == 9) {
            // abp.ui.setBusy(undefined, '', 1);
            this._bopNodeServiceProxy.getWorkStepOut(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    if (result.workStepOut.workStepCharacteristic != null) {
                        this.workStepCheck = result.workStepOut.workStepCharacteristic.split('|');
                        this.workStepCheck.splice(this.workStepCheck.length - 1, 1);
                    }
                    this.workstepInfo = result;
                    //abp.ui.clearBusy();
                    this.onTabChange({ index: 0 });

                });
        }
        // 路线管理
        this._processRouteServiceProxy.getProcessNodeById(event.node.id)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.diagram.model.nodeDataArray = result.processNodeList;
                let processLineList = result.processLineList;
                if (result.processLineList != null) {
                    let linkdata = [];
                    for (const item of processLineList) {
                        let link = { points: '', from: '', to: '', color: '' };
                        if (item.points) {
                            link.points = JSON.parse(item.points);
                        }
                        if (item.color) {
                            link.color = item.color;
                        }
                        link.from = item.from;
                        link.to = item.to;
                        linkdata.push(link)
                    }
                    this.diagram.model.linkDataArray = linkdata;
                } else {
                    this.diagram.model.linkDataArray = [];
                }
                // this.diagram.model.linkDataArray = [{from: "645c20a5-0561-4c7f-1c28-08d950ae8880",to: "9018e7d2-008d-4f14-2496-08d950a15df3"}]
                this.diagram.div = this.diagramRef.nativeElement;
                this.mapMsg.parentId = event.node.id;
            });

    }
    // 递归循环树级结构 获取对象 通过物料ID 递归
    getTreeRecursion(data, current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getTreeRecursion(item.children, current);
            }
        }
        return result;
    }
    //导出规程
    toExcelItem() {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        this.dataExport.show();
        this.exportData = {
            id: this.ischeckTree.id,
            parentId: this.ischeckTree.parentId,
            nodeLevel: this.ischeckTree.nodeLevel,
            processId: this.ischeckTree.id
        }
    }
    show(): void {
        this.active = true;
        this.parentInfo.creationworkingHour = moment(this.parentInfo.creationworkingHour).format('YYYY-MM-DD HH:mm:ss');
        this.modal.show();
    }
    //bop部套保存
    save(): void {
        // if (!this.btInfo.remark) {
        //     this._messageService.info('备注为空');
        //     return;
        // }
        // let params = new CreateOrUpdateBopContentInput();
        // params.bopContent = this.bopContent;
        // params.bopContent.bopNodeId = this.ischeckTree.id;
        // params.bopContent.remark = this.btInfo.remark;
        // params.bopContent.id = this.btInfo.contentId;
        // this._bopContentServiceProxy.createOrUpdateBopContent(
        //     params
        // )
        //     .pipe(finalize(() => { this.loading = false; }))
        //     .subscribe(result => {
        //         this._messageService.success('保存成功');
        //     });
    }
    expandAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }

    collapseAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, false);
        });
    }
    exdents(oldNode) {
        for (let i = 0; i < this.files2.length; i++) {
            if (this.files2[i].id == oldNode[i].id) {
                this.exdentsNode(oldNode[i], this.files2[i]);
            }

        }
    }
    //新增BOP树结构
    insertBopTree(key): void {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        if (parseInt(this.ischeckTree.nodeLevel) + 1 > 3 && key) {
            this._messageService.info('节点最多只能添加四级');
            return;
        }
        if (parseInt(this.ischeckTree.nodeLevel) > 4 && !key) {
            this._messageService.info('不可编辑工序及工步节点');
            return;
        }
        this.createOrEditBopTreeModal.show(key, this.ischeckTree);

    }
    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    private exdentsNode(oldNode, newNode) {
        if (oldNode != undefined) {
            if (oldNode.id == newNode.id) {
                newNode.expanded = oldNode.expanded;
                if (newNode.children) {
                    for (let i = 0; i < newNode.children.length; i++) {
                        this.exdentsNode(oldNode.children[i], newNode.children[i]);
                    }
                }
            }
        }
    }
    close(): void {
        this.active = false;
        this.files2 = [];
        this.btInfo = new BopContentInfoDto();
        this.processFile = new TechniqueDto();
        this.btInfoDate = undefined;
        this.btInfoNewDate = undefined;
        this.mapMsg.bopDescId = undefined;
        this.modal.hide();
    }

    //解绑节点
    backItem() {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        //1为绑定 0为未绑定
        if (this.ischeckTree.isRelation != 1) {
            this._messageService.info('该节点没有关联工艺规程');
            return;
        }
        this.message.confirm(
            '确认解绑' + this.ischeckTree.nodeName + '的工艺规程吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._bopNodeServiceProxy
                            .unbindNode(this.ischeckTree.id)
                            .subscribe((result) => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.getTreeInfo(false);
                                    this._messageService.success('解绑成功');
                                } else {
                                    this._messageService.error(result.message)
                                }

                            });
                    }
                }
            }
        );


    }
    //tab 切换工步动态表
    onTabChange(event) {
        this.workStepHeader = this.workstepInfo.tableNameDictionary[event.index];
        this.workStepData = this.workstepInfo.workStepOut[this.workstepInfo.tableNameDictionary[event.index].tablekey];
    }
    //删除bop节点
    deleteItem(): void {
        if (Object.keys(this.ischeckTree).length == 0) {
            this._messageService.info('请选择一个节点');
            return;
        }
        //8和9为工序和工部
        if (parseInt(this.ischeckTree.nodeLevel) == 8 || parseInt(this.ischeckTree.nodeLevel) == 9) {
            this._messageService.info('该节点不可删除');
            return;
        }
        this.message.confirm(
            '确认删除' + this.ischeckTree.nodeName + '吗',
            (isConfirmed) => {
                if (isConfirmed) {
                    // if (this.saveFlag) {
                    //     this.saveFlag = false;
                    this._bopNodeServiceProxy
                        .deleteBopNode(this.ischeckTree.id)
                        .subscribe(() => {
                            // this.saveFlag = true;
                            this.getTreeInfo(true);
                            this._messageService.success('删除成功');
                        });
                    // }

                }
            }
        );
    }

}
